package org.batch.service.business.impl;

import org.batch.entity.Trading;
import org.batch.mapper.TradingMapper;
import org.batch.service.business.AccountService;
import org.batch.service.business.TradingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import static java.math.BigDecimal.ZERO;
import static org.batch.constant.Constant.EFFECTIVE_E;

/**
 * 交易数据相关业务逻辑接口实现
 *
 * @author LiKun
 * @date 2021/9/29 14:14
 */
@Service
public class TradingServiceImpl implements TradingService {
    private static final Logger logger = LoggerFactory.getLogger(TradingServiceImpl.class);

    @Resource
    private TradingMapper tradingMapper;
    @Resource
    private AccountService accountService;

    @PostConstruct
    private void initialize() {
        logger.info("加载交易数据处理接口TradingServiceImpl成功");
    }

    @Override
    @Transactional
    public int insertTrading(@NotNull Trading trading) {
        return tradingMapper.insert(trading);
    }

    @Override
    @Transactional
    public void batchInsertTrading(@NotEmpty List<Trading> tradings) {
        tradingMapper.batchInsert(tradings);
    }

    @Override
    @Transactional
    public void batchDealTrading(@NotEmpty String id, @NotEmpty List<Trading> tradings) throws Exception {
        AtomicReference<BigDecimal> reference = new AtomicReference<>(ZERO);
        tradings.forEach(val -> {
            try {
                tradingMapper.updateEffective(val.getId(), EFFECTIVE_E);
                reference.set(reference.get().add(val.getTradeAmount()));
            } catch (Exception e) {
                logger.info("更新对象{}的有效标识失败", val);
            }
        });
        accountService.updateBalance(id, reference.get());
    }
}
